//
//  STAdmobBannerView.swift
//  iPhone
//
//  Created by Toj on 5/25/23.
//

import UIKit
import GoogleMobileAds

protocol STAdmobBannerViewDelegate: NSObjectProtocol {
    func admobBannerViewLoadedSuccess(_ bannerView: STAdmobBannerView, cellModel: BannerAdCellModel?)
    func admobBannerViewLoadedFaild(_ bannerView: STAdmobBannerView, cellModel: BannerAdCellModel?, error: Error?)
    func admobBannerViewShowed(_ bannerView: STAdmobBannerView, cellModel: BannerAdCellModel?)
}

class STAdmobBannerView: UIView {
    
    weak var delegate: STAdmobBannerViewDelegate?
    
    private(set) var _adView: GADBannerView?
    
    var cellModel: BannerAdCellModel? { willSet {
        guard let model = newValue else { return }
        guard !model.adUnitID.isEmpty else { return }
        // 刷新的是新View
        // 刷新的是要显示的View
        if let adView = model.adView {
            adView.removeFromSuperview()
            addSubview(adView)
            adView.snp.makeConstraints { make in
                make.edges.equalTo(self)
            }
            return
        }
        
        setupAdView(model: model)
    } }
    
    func setupAdView(model: BannerAdCellModel) {
        print("-->toj: func:\(#function), adUnitID:\(model.adUnitID)")
        let size = GADAdSizeFromCGSize(model.willShowCellSize)
        let adView = GADBannerView(adSize: size)
        adView.adUnitID = model.adUnitID
        adView.rootViewController = UIViewController.vc_currentNavigationTopViewController
        adView.delegate = self
        adView.adUnitID = model.adUnitID
        adView.load(GADRequest())
        
        _adView = adView
    }
}

extension STAdmobBannerView: GADBannerViewDelegate {
    
    func bannerViewDidReceiveAd(_ bannerView: GADBannerView) {
        guard _adView == bannerView else  {return }
        let adUnitID = bannerView.adUnitID ?? ""
        print("-->toj: func:\(#function), adUnitID:\(adUnitID)")
 
        cellModel?.adView = _adView
        delegate?.admobBannerViewLoadedSuccess(self, cellModel: cellModel)
    }
    
    func bannerView(_ bannerView: GADBannerView, didFailToReceiveAdWithError error: Error) {
        guard _adView == bannerView else  {return }
        let adUnitID = bannerView.adUnitID ?? ""
        print("-->toj: func:\(#function), adUnitID:\(adUnitID)")
        print("-->toj: func: \(#function) msg: \(error.localizedDescription)")
        cellModel?.isNeedLayout = false
        delegate?.admobBannerViewLoadedFaild(self, cellModel: cellModel, error: error)
    }
    
    func bannerViewDidRecordImpression(_ bannerView: GADBannerView) {
        guard _adView == bannerView else  {return }
        
        cellModel?.isNeedLayout = true
        print("-->toj: func: \(#function)")
        delegate?.admobBannerViewShowed(self, cellModel: cellModel)
    }
}
